package com.symaster.common.swing.ui.button;

import sun.swing.SwingUtilities2;

import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;

/**
 * @author yinmiao
 * @date 2021-11-27 18:40
 */
public class MyButtonUI extends BasicButtonUI {

    private final Rectangle viewRect = new Rectangle();
    private final Rectangle textRect = new Rectangle();
    private final Rectangle iconRect = new Rectangle();

    @Override
    public void update(Graphics g, JComponent c) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (c.isOpaque()) {
            g2d.setColor(c.getBackground());
            g2d.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 12, 12);
        }
        paint(g2d, c);
    }

    protected void paintButtonPressed(Graphics g2d, AbstractButton b) {
        g2d.setColor(new Color(0, 255, 0));
        g2d.fillRect(0, 0, 50, 50);
    }

    @Override
    public void paint(Graphics g2d, JComponent c) {
        AbstractButton b = (AbstractButton) c;
        ButtonModel model = b.getModel();

        String text = layout(b, SwingUtilities2.getFontMetrics(b, g2d), b.getWidth(), b.getHeight());

        g2d.setColor(new Color(255, 255, 255));
        g2d.drawString(text, textRect.x, textRect.y + 10);

        // perform UI specific press action, e.g. Windows L&F shifts text
        if (model.isPressed()) {
            paintButtonPressed(g2d, b);
        }

        if (b.isFocusPainted() && b.hasFocus()) {
            // paint UI specific focus
            paintFocus(g2d, b, viewRect, textRect, iconRect);
        }
    }

    // Method signature defined here overriden in subclasses.
    // Perhaps this class should be abstract?
    protected void paintFocus(Graphics g2d, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {

        g2d.setColor(new Color(255, 20, 0, 255));
        g2d.fillRect(0, 0, 50, 50);
    }

    private String layout(AbstractButton b, FontMetrics fm, int width, int height) {
        Insets i = b.getInsets();
        viewRect.x = i.left;
        viewRect.y = i.top;
        viewRect.width = width - (i.right + viewRect.x);
        viewRect.height = height - (i.bottom + viewRect.y);

        textRect.x = textRect.y = textRect.width = textRect.height = 0;
        iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;

        // layout the text and icon
        return SwingUtilities.layoutCompoundLabel(b, fm, b.getText(), b.getIcon(), b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewRect, iconRect, textRect, b.getText() == null ? 0 : b.getIconTextGap());
    }

}
